import http from '@/shopro/request/index'
import https from '@/shopro/requests/index'
import share from '@/shopro/share';
import Auth from '@/shopro/permission/index.js';
import qqmapsdk from '@/shopro/mixins/qqmap-wx-jssdk.min.js';
const QQMapWX = new qqmapsdk({
	key: 'DCTBZ-MQ5L4-PRPUC-DWELG-IUUYH-G5BFA' //开发者密钥 腾讯地图key
});
const state = {
	shop: {}, // 商城信息
	wechat: {}, // 微信配置
	share: {}, // 分享配置
	payment: {}, // 支付配置
	addons: [], // 插件配置
	chat: uni.getStorageSync("chat") || {}, // 客服配置
	store: {}, // 商城信息
	tabbarData: [], //自定义底部导航数据

	homeTemplate: [], // 首页模板数据
	userTemplate: [], // 个人中心模板数据
	floatData: {}, // 悬浮按钮数据
	popupData: {}, // 弹窗数据
	hasTemplate: true, //是否有模板数据
	shareInfo: {}, // 默认分享数据
	latitude:uni.getStorageSync("latitude") || "",//纬度
	longitude:uni.getStorageSync("longitude") || "",//经度
}
const getters = {
	initShop: state => state.shop,
	initStore: state => state.store,
	initShare: state => state.share,
	initPayment: state => state.payment,
	initAddons: state => state.addons,
	initChat: state => state.chat,
	initWechat: state => state.wechat,

	hasTemplate: state => state.hasTemplate,
	homeTemplate: state => state.homeTemplate,
	userTemplate: state => state.userTemplate,
	floatData: state => state.floatData,
	popupData: state => state.popupData,
	tabbarData: state => state.tabbarData,

	shareInfo: state => state.shareInfo,
	latitude: state => state.latitude,
	longitude: state => state.longitude
}


const actions = {
	// 地址选择
	async locationAddress({
		  commit
	  }, options){
		console.log("========1111")
		let authState = await new Auth('userLocation').check();
		authState &&
		uni.getLocation({
			type: "wgs84", //默认为 wgs84 返回 gps 坐标
			geocode: "true",
			isHighAccuracy: "true",
			accuracy: "best",
			success: res => {
				let locationModel = {
					latitude : res.latitude,
					longitude : res.longitude
				}
				commit('LOCATION_MODEL', locationModel);
				console.log("======res.latitude",res.latitude,"=============res.longitude",res.longitude)
				uni.setStorageSync("latitude", res.latitude);
				uni.setStorageSync("longitude", res.longitude);
				console.log("uni.getStorageSync('latitude')========",uni.getStorageSync("latitude"))
				// 解析地址
				QQMapWX.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude:  res.longitude
					},
					success: function(res1) {
						console.log('解析地址成功');
						console.log(res1);
						// 省
						// let province = res.result.ad_info.province;
						// 市
						let city = res1.result.ad_info.city;
						uni.setStorageSync("city", city);
						console.log("======city",city);
					},
					fail: function(res2) {
						uni.showToast({
							title: '定位失败',
							duration: 2000,
							icon: 'none'
						});
						console.log(res2);
					},
					complete: function(res3) { //无论成功失败都会执行
						console.log(res3);
					}
				});
			},
			fail: err => {
				console.log(err);
			}
		});
	},

	// 初始化数据
	async appInit({
		commit,
		dispatch
	}, options) {
		const result = await http('common.init');
		if (result.code === 1) {
			commit('CONFIG', result.data);
			if (!options?.query?.token) {
				dispatch('autoLogin');
			}
			return result.data;
		}
		return false;
	},

	// 获取模板数据
	async getTemplate({
		dispatch,
		commit
	}, options) {
		console.log("========2222")
		let shop_id = 0;
		// #ifdef H5
		if (options?.query.shop_id) {
			shop_id = options.query.shop_id;
		}
		// #endif

		// #ifdef MP
		if (options?.query.scene) {
			let scene = decodeURIComponent(options?.query.scene);
			let sceneObj = scene.split('=');
			if (sceneObj[0] === 'shop_id') {
				shop_id = sceneObj[1]
			}
		}
		// #endif
		const result = await http('common.template', shop_id ? {
			shop_id
		} : {});
		if (result.code === 1) {
			commit("hasTemplate", true);
			const result_index = await https('common.template_index', {
				'latitude':uni.getStorageSync("latitude") || "",//纬度
				'longitude':uni.getStorageSync("longitude") || "",//经度
				"token":uni.getStorageSync("token")||''
			});
			let data = {
				"home": [
					{
						"id": 15424,
						"type": "menu",
						"category": "home",
						"name": "菜单组",
						"content": {
							"name": "",
							"style": 4,
							"list": []
						},
						"decorate_id": 1
					},
					{
						"id": 15423,
						"type": "banner",
						"category": "home",
						"name": "轮播图",
						"content": {
							"name": "",
							"style": 1,
							"height": 120,
							"radius": 10,
							"x": 20,
							"y": 10,
							"list": []
						},
						"decorate_id": 1
					},
					{
						"id": 15427,
						"type": "groupon",
						"category": "home",
						"name": "秒杀",
						"content": {
							"id": 2,
							"name": "特价拼团",
							"style": 1,
							"groupon_name": "拼团专场",
							"team_num": "3"
						},
						"decorate_id": 1
					},
					{
						"id": 15431,
						"type": "category-tabs",
						"category": "home",
						"name": "分类选项卡",
						"content": {
							"ids": "'',69,70,71,72",
							"category_arr": [
								{
									"id": 44,
									"name": "多米商邦",
									"type": "",
									"image": "http://file.shopro.top/uploads/20210519/b505c4c6c4aefdb3467877f2ef21c534.jpeg",
									"pid": 43,
									"weigh": 0,
									"description": "",
									"status": "normal",
									"createtime": 1621406730,
									"updatetime": 1650699272,
									"children": []
								},
								{
									"id": 69,
									"name": "多米惠选",
									"type": "",
									"image": "http://file.shopro.top/uploads/20210519/b330cd09cd55c038c1743aef21545241.png",
									"pid": 43,
									"weigh": 0,
									"description": "",
									"status": "normal",
									"createtime": 1621407282,
									"updatetime": 1650699272,
									"children": []
								},
								{
									"id": 70,
									"name": "米包多多",
									"type": "",
									"image": "http://file.shopro.top/uploads/20210519/225422d99ca344883fc5a1a52a6f2ad5.png",
									"pid": 43,
									"weigh": 0,
									"description": "",
									"status": "normal",
									"createtime": 1621407282,
									"updatetime": 1650699272,
									"children": []
								},
							],
							"style": 2
						},
						"decorate_id": 1
					}
				],
				"popup": [
					{
						"id": 15432,
						"type": "popup",
						"category": "popup",
						"name": "弹窗提醒",
						"content": {
							"list": [
								{
									"name": "",
									"style": 1,
									"image": "http://file.shopro.top/uploads/20210518/9136ecddcddf6607184fab689207e7e3.png",
									"btnimage": "",
									"path": "/pages/app/coupon/list",
									"path_name": "优惠券中心",
									"path_type": 1
								}
							]
						},
						"decorate_id": 1
					}
				],
			}
			data.home.forEach((item,index)=>{
				if(item.type == 'banner'){
					item.content.list = result_index.data.lunbo;
				}
				if(item.type == 'menu'){
					item.content.list = result_index.data.cate;
				}
				if(item.type == 'groupon'){
					item.content.list = result_index.data.miaosha;
				}
				if(item.type == 'category-tabs'){
					item.content.category_arr[0].children = result_index.data.shangbang;
					item.content.category_arr[1].children = result_index.data.huixuan;
					item.content.category_arr[2].children = result_index.data.mibao;
				}
			})
			commit('TEMPLATE', data);
			return data;
		} else {
			commit("hasTemplate", false);
			return false;
		}
	},

	// 同步路由到后端
	syncPages({
		commit
	}) {
		http('common.syncPages', {
			data: ROUTES,
		})
	},
}


const mutations = {
	LOCATION_MODEL(state, data){
		state.latitude = data.latitude;
		state.longitude = data.longitude;
		console.log("loactiondata==========",state)
		uni.setStorageSync("latitude", data.latitude);
		uni.setStorageSync("longitude", data.longitude);
	},
	CONFIG(state, payload) {
		Object.keys(payload).forEach(k => {
			state[k] = payload[k];
			if (k === 'chat') {
				uni.setStorageSync("chat", payload[k]);
			}
		})
	},

	TEMPLATE(state, data) {
		state.template = data;
		state.homeTemplate = data.home
		state.userTemplate = data.user
		state.floatData = data['float-button']?. [0]?.content
		state.popupData = data?.popup?. [0]?.content
		state.tabbarData = data?.tabbar?. [0]?.content
	},

	hasTemplate(state, data) {
		state.hasTemplate = data
	},
	// 弹窗一次的话，关闭的时候删除数据。
	delPopup(state, index) {
		let popupData = state.popupData;
		popupData.list.splice(index, 1)
		state.template = popupData;
	},
	shareInfo(state, shareInfo) {
		state.shareInfo = shareInfo;
	}
}


export default {
	state,
	mutations,
	actions,
	getters
}
